#include "park_manager.h"

namespace application {
namespace park {

ParkManager::ParkManager(int floor, std::shared_ptr<kernel::ILogger> logger, QObject* parent)
    : QObject(parent)
    , m_floor(floor)
    , m_logger(logger)
{
}

void ParkManager::addParkPoint(std::shared_ptr<ParkPoint> parkPoint) {
    if (!parkPoint) {
        if (m_logger) {
            m_logger->warning("尝试添加空停车点对象");
        }
        return;
    }

    QString pointId = parkPoint->getPointId();
    m_parkPoints.insert(pointId, parkPoint);

    if (m_logger) {
        m_logger->debug(QString("停车点已添加: %1 (楼层: %2)").arg(pointId).arg(m_floor));
    }

    // 连接信号，监听停车点可用性变化
    connect(parkPoint.get(), &ParkPoint::occupationChanged, this,
        [this, pointId](bool occupied, int agvId) {
            Q_UNUSED(agvId);
            emit parkPointAvailabilityChanged(pointId, !occupied);
        });

    emit parkPointAdded(pointId);
}

void ParkManager::removeParkPoint(const QString& pointId) {
    if (m_parkPoints.remove(pointId) > 0) {
        if (m_logger) {
            m_logger->debug(QString("停车点已移除: %1").arg(pointId));
        }
        emit parkPointRemoved(pointId);
    }
}

std::shared_ptr<ParkPoint> ParkManager::getParkPoint(const QString& pointId) const {
    return m_parkPoints.value(pointId, nullptr);
}

bool ParkManager::hasParkPoint(const QString& pointId) const {
    return m_parkPoints.contains(pointId);
}

QList<QString> ParkManager::getAllParkPointIds() const {
    return m_parkPoints.keys();
}

std::shared_ptr<ParkPoint> ParkManager::findAvailableParkPoint() const {
    for (auto it = m_parkPoints.constBegin(); it != m_parkPoints.constEnd(); ++it) {
        if (!it.value()->isOccupied() && !it.value()->isPreOccupied()) {
            return it.value();
        }
    }
    return nullptr;
}

QList<std::shared_ptr<ParkPoint>> ParkManager::getAvailableParkPoints() const {
    QList<std::shared_ptr<ParkPoint>> availablePoints;
    for (auto it = m_parkPoints.constBegin(); it != m_parkPoints.constEnd(); ++it) {
        if (!it.value()->isOccupied() && !it.value()->isPreOccupied()) {
            availablePoints.append(it.value());
        }
    }
    return availablePoints;
}

void ParkManager::initializeParkPoints() {
    if (m_logger) {
        m_logger->info(QString("初始化楼层 %1 的停车点管理器").arg(m_floor));
    }
    // 这里可以从配置或地图数据加载停车点信息
}

} // namespace park
} // namespace application
